package com.qf.servlet;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * projectName:my_profile
 * author:luo
 * time:2023/1/30 9:29
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-context.xml");
    UserService userService = ac.getBean(UserService.class);
    public String userRegist(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3调用业务逻辑
        try {
            userService.regist(username,password);
            return "/login.jsp";
        } catch (Exception e) {
            request.setAttribute("error","注册失败"+e.getMessage());
            return "/error.jsp";
        }
    }
    public void userCheck(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2非空验证
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("1");
            return ;
        }
        if (StringUtils.isEmpty(password)) {
            response.getWriter().write("2");
            return ;
        }
        boolean b=userService.checkUser(username);
        if (b){
            response.getWriter().write("3");
            return;
        }
        response.getWriter().write("0");
    }
    public String userLogin(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);
        //2非空验证
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("1");
            return null;
        }
        if (StringUtils.isEmpty(password)) {
            response.getWriter().write("2");
            return null;
        }
        try {
            //3调用业务逻辑
            User user=userService.login(username,password);
            request.getSession().setAttribute("user",user);
            return "/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","登录失败"+e.getMessage());
            return "/error.jsp";
        }
    }

}
